/*! ******************************************************************************
 *
 * Created on 2022年6月11日
 *
 * Copyright(c) YuZhou Big Data Laboratory CO.,Ltd, 2022.  All rights reserved.
 *
 *******************************************************************************
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/
package org.pentaho.di.ui.spoon.navigation.design.classification.plugin;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.LaniusPluginTreeItem;
import org.yzbdl.lanius.core.plugins.metastore.LdrPluginEntity;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.ui.core.ConstUI;
import org.pentaho.di.ui.core.gui.LaniusGuiResource;
import org.pentaho.di.ui.core.gui.GUIResource;
import org.pentaho.di.ui.spoon.navigation.Bundle;
import org.pentaho.di.ui.spoon.navigation.design.classification.Classification;
import org.pentaho.di.ui.spoon.navigation.design.classification.category.Category;
import org.pentaho.di.ui.util.PinyinUtils;

import java.util.Objects;

/**
 * //
 *
 * @author hs@yzbdl.ac.cn
 * @version 1.0
 * @date 2019-06-14 9:01
 */
public class Plugin extends Bundle {
    /**
     * data
     */
    protected LdrPluginEntity ldrPluginEntity;

    /**
     * view
     */
    protected LaniusPluginTreeItem treeItem;

    protected Bundle parent;

    public Plugin() {
        super(null);
    }

    public Plugin(Bundle parent, LdrPluginEntity ldrPluginEntity) {
        super(parent.getSpoon());
        this.parent = parent;
        this.ldrPluginEntity = ldrPluginEntity;
        
        // 匹配搜索，则显示
        if (filterMatch(this.ldrPluginEntity.getName())) {
            if (parent instanceof Classification) {
            	this.treeItem = new LaniusPluginTreeItem(((Classification) parent).getTree(), SWT.SIMPLE, this.getPluginEntity(), getName(), getImage());
            }
            if (parent instanceof Category) {
                this.treeItem = new LaniusPluginTreeItem(((Category) parent).getTreeItem(), SWT.SIMPLE, this.getPluginEntity(), getName(), getImage());
            }
            if (parent instanceof PluginVersion) {
                this.treeItem = new LaniusPluginTreeItem(((PluginVersion) parent).getTreeItem(), SWT.SIMPLE, this.getPluginEntity(), getName(), getImage());
            }
        } 
        // 否则不显示，则销毁
        else if (this.treeItem != null) {
            this.treeItem.dispose();
            this.treeItem = null;
        }
    }

    public boolean isNull() {
        return this.treeItem == null || this.treeItem.isDisposed();
    }

    public boolean isNotNull() {
        return this.treeItem != null && !this.treeItem.isDisposed();
    }

    /**
     * 判断是否匹配搜索（搜索栏为空字符串时，全部匹配）
     * @param string 插件名称
     * @return true 显示; false 不显示
     */
    private boolean filterMatch(String string) {
        if (Utils.isEmpty(string)) {
            return true;
        }

        String filter = this.getSpoon().selectionFilter.getText();
        if (Utils.isEmpty(filter)) {
            return true;
        }
        PinyinUtils pinyinUtils = new PinyinUtils();
        String pinyin = pinyinUtils.getPinyin(string).toLowerCase();
        String pinyinFilter = pinyinUtils.getPinyin(filter).toLowerCase();
        String fisrtSpell = pinyinUtils.getFisrtSpell(string).toLowerCase();
        try {
            if (string.matches(filter)) {
                return true;
            }
            if (pinyin.matches(pinyinFilter) | fisrtSpell.matches(pinyinFilter)) {
                return true;
            }
        } catch (Exception e) {
        }
        return pinyin.toUpperCase().contains(pinyinFilter.toUpperCase()) | fisrtSpell.toUpperCase()
            .contains(pinyinFilter.toUpperCase());
    }

    public String getName() {
        return this.getPluginEntity().getName();
    }

    public Image getImage() {
    	Image image = null;
//    	String pluginTypeClass = this.getPluginEntity().getPluginTypeClass();
    	try {
//    		String imageFile = this.getPluginEntity().getPluginImage();
//    		String imageFile = this.getPluginEntity().getImage();
//			PluginRegistry registry = PluginRegistry.getInstance();
//			FuncType funcType = FuncType.getById(this.getPluginEntity().getFuncType());
//			Class cls = Class.forName(this.getPluginEntity().getPluginTypeClass());
//			PluginInterface pi = registry.findPluginWithId(cls, this.getPluginEntity().getPluginId());
//			PluginInterface pi = registry.findPluginWithId(Func2PluginTypeClass.getBy(funcType), this.getPluginEntity().getPluginId());
//			ClassLoader classLoader = registry.getClassLoader(pi);
//			image = GUIResource.getInstance().getImage(imageFile, classLoader, ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
			String pluginFolder = this.getPluginEntity().getFolderName();
			String version = this.getPluginEntity().getVersion();
			if(version.equals("none")) {
                image = GUIResource.getInstance().getImage(ldrPluginEntity.getImage(), ldrPluginEntity.getMainClass().getClassLoader(), ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
            }
			else {
                image = LaniusGuiResource.getInstance().getPluginImage(pluginFolder, version, ConstUI.MEDIUM_ICON_SIZE);
            }
        } catch (Exception e) {
			image = GUIResource.getInstance().getImageNoImage(ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
		}
    	
//    	if(JobEntryPluginType.class.getName().equals(pluginTypeClass)) {
//    		image = GUIResource.getInstance().getImagesJobentries().get(getStrIds()[0])
//                    .getAsBitmapForSize(this.getSpoon().getDisplay(), ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    	}else if(StepPluginType.class.getName().equals(pluginTypeClass)) {
//    		image = GUIResource.getInstance().getImagesSteps().get(getStrIds()[0])
//                    .getAsBitmapForSize(this.getSpoon().getDisplay(), ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    	}else {
//    		try {
//        		String imageFile = this.getPluginEntity().getPluginImage();
//    			PluginRegistry registry = PluginRegistry.getInstance();
//    			
////    			FuncType funcType = FuncType.getById(this.getPluginEntity().getFuncType());
//    			Class cls = Class.forName(this.getPluginEntity().getPluginTypeClass());
//    			PluginInterface pi = registry.findPluginWithId(cls, this.getPluginEntity().getPluginId());
////    			PluginInterface pi = registry.findPluginWithId(Func2PluginTypeClass.getBy(funcType), this.getPluginEntity().getPluginId());
//    			ClassLoader classLoader = registry.getClassLoader(pi);
//    			image = GUIResource.getInstance().getImage(imageFile, classLoader, ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    		} catch (Exception e) {
//    			image = GUIResource.getInstance().getImageNoImage(ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    		}
//    	}
    	
//        if (FuncType.Jobs.getId() == this.getPluginEntity().getFuncType()) {
//        	image = GUIResource.getInstance().getImagesJobentries().get(getStrIds()[0])
//                .getAsBitmapForSize(this.getSpoon().getDisplay(), ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//        }else if (FuncType.Trans.getId() == this.getPluginEntity().getFuncType()) {
//        	image = GUIResource.getInstance().getImagesSteps().get(getStrIds()[0])
//                .getAsBitmapForSize(this.getSpoon().getDisplay(), ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//        }else {
//        	try {
//        		String imageFile = this.getPluginEntity().getPluginImage();
//    			PluginRegistry registry = PluginRegistry.getInstance();
//    			FuncType funcType = FuncType.getById(this.getPluginEntity().getFuncType());
//    			PluginInterface pi = registry.findPluginWithId(Func2PluginTypeClass.getBy(funcType), this.getPluginEntity().getPluginId());
//    			ClassLoader classLoader = registry.getClassLoader(pi);
//    			image = GUIResource.getInstance().getImage(imageFile, classLoader, ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    		} catch (Exception e) {
//    			image = GUIResource.getInstance().getImageNoImage(ConstUI.MEDIUM_ICON_SIZE, ConstUI.MEDIUM_ICON_SIZE);
//    		}
//        }
    	return image;
    }

    public String[] getStrIds() {
        return this.getPluginEntity().getPluginId().split(",");
    }

    public String getStrId() {
        return this.getPluginEntity().getPluginId();
    }

    public Integer getId() {
        return this.getPluginEntity().getId();
    }

    public LdrPluginEntity getPluginEntity() {
        return ldrPluginEntity;
    }

    public void setPluginEntity(LdrPluginEntity ldrPluginEntity) {
        this.ldrPluginEntity = ldrPluginEntity;
    }

    public LaniusPluginTreeItem getTreeItem() {
        return treeItem;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Plugin plugin = (Plugin) o;
        return Objects.equals(this.getPluginEntity().getId(), plugin.getPluginEntity().getId()) && Objects
            .equals(this.getPluginEntity().getPluginId(), plugin.getPluginEntity().getPluginId()) && Objects
            .equals(this.getPluginEntity().getVersion(), plugin.getPluginEntity().getVersion());
    }

    @Override
    public int hashCode() {
        return Objects.hash(this.getPluginEntity().getId(), this.getPluginEntity().getPluginId(), this.getPluginEntity().getVersion());
    }
}
